//
//  lcbImageView.m
//  lcbImageView
//
//  Created by lcb on 16/6/12.
//  Copyright © 2016年 lcb. All rights reserved.
//

#import "LcbImageView.h"
#import "UIImageView+WebCache.h"
#import "SDWebImageDownloader.h"
#import "SDWebImageManager.h"

@implementation UIImageView (lcbImageView)
- (void)lcb_imageWithUrlStr:(NSString *)urlStr {
    
    [self lcb_imageWithUrlStr:urlStr placeholder:nil progressBlock:nil completedBlock:nil];
}

- (void)lcb_imageWithUrlStr:(NSString *)urlStr placeholder:(UIImage *)placeholder {
    
    [self lcb_imageWithUrlStr:urlStr placeholder:placeholder progressBlock:nil completedBlock:nil];
}

- (void)lcb_imageWithUrlStr:(NSString *)urlStr placeholderImage:(UIImage *)placeholder completedBlock:(lcbImageViewCompletionBlock)completedBlock {
    
    [self lcb_imageWithUrlStr:urlStr placeholder:placeholder progressBlock:nil completedBlock:completedBlock];
}

- (void)lcb_imageWithUrlStr:(NSString *)urlStr placeholder:(UIImage *)placeholder progressBlock:(lcbImageViewDownloaderProgressBlock)progressBlock completedBlock:(lcbImageViewCompletionBlock)completedBlock {
    
    NSURL *url = [self encodeURLWithString:urlStr];
    
    [self setShowActivityIndicatorView:NO];
    SDWebImageOptions options = SDWebImageLowPriority | SDWebImageRetryFailed | SDWebImageDownloaderProgressiveDownload;
    [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        if (progressBlock) {
            progressBlock(receivedSize,expectedSize);
        }
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        if (completedBlock) {
            completedBlock(image,error,imageURL);
        }
    }];
}

/*!
 @method
 @abstract 根据url字符串来生成NSURL，如果包含中文就进行转码
 @discussion @c[self encodeURLWithString:@“”];
 @param  urlString 图片网络地址
 @result url相应的NSURL
 */
- (NSURL *)encodeURLWithString:(NSString *)urlString {
    
    if (!urlString) {
        return nil;
    }
    
    NSURL *encodeURL = [NSURL URLWithString:urlString];
    // 判断图片链接中是否含有汉字，如果存在则先对链接编码
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[\\u4e00-\\u9fa5]" options:NSRegularExpressionCaseInsensitive error:nil];
    if ([regex numberOfMatchesInString:urlString options:0 range:NSMakeRange(0, [urlString length])] > 0) {
        NSString *encodeString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        encodeURL = [NSURL URLWithString:encodeString];
    }
    
    return encodeURL;
}
@end
